package com.example.enjoyfood

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.widget.ImageView
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken

class ShopFragment : Fragment() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var cartView: TextView
    private lateinit var totalPriceButton: Button
    private lateinit var viewCartButton: Button
    private val cartItems = mutableMapOf<Product, Int>() // 使用 Map 记录商品和数量
    private lateinit var sharedPreferences: SharedPreferences

    private val products = listOf(
        Product("调味品集合", R.drawable.product1, 59.99),
        Product("电磁炉", R.drawable.product2, 499.99),
        Product("洗碗机", R.drawable.product3, 999.99),
        Product("洗洁精", R.drawable.product4, 19.99),
        Product("手套", R.drawable.product5, 6.99),
        Product("蛋挞壳", R.drawable.product6, 89.99),
        Product("保鲜盒", R.drawable.product7, 29.99),
        Product("高压锅", R.drawable.product8, 599.99),
        Product("菜刀", R.drawable.product9, 399.99),
        Product("豆浆机", R.drawable.product10, 249.99)
    )

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_shop, container, false)

        recyclerView = view.findViewById(R.id.recycler_view)
        cartView = view.findViewById(R.id.cart_view)
        totalPriceButton = view.findViewById(R.id.button_checkout)
        viewCartButton = view.findViewById(R.id.button_view_cart)

        recyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
        recyclerView.adapter = ProductAdapter(products)

        totalPriceButton.setOnClickListener {
            showCheckoutDialog()
        }

        viewCartButton.setOnClickListener {
            showCartDialog()
        }

        sharedPreferences = requireContext().getSharedPreferences("cart_prefs", Context.MODE_PRIVATE)
        loadCartItems()

        return view
    }

    private fun showCheckoutDialog() {
        val builder = AlertDialog.Builder(requireContext())
        builder.setTitle("结算")

        val items = cartItems.map { "${it.key.name} x${it.value}" }
        val totalPrice = cartItems.entries.sumByDouble { it.key.price * it.value }
        val formattedTotalPrice = String.format("%.2f", totalPrice)

        builder.setMessage("购物车商品: ${if (items.isEmpty()) "无" else items.joinToString(", ")}\n总价: ￥$formattedTotalPrice")
        builder.setPositiveButton("确认") { dialog, _ ->
            // 进行结算流程
            dialog.dismiss()
        }
        builder.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }

        builder.create().show()
    }

    private fun showCartDialog() {
        val builder = AlertDialog.Builder(requireContext())
        builder.setTitle("购物车")

        val items = cartItems.map { "${it.key.name} x${it.value}" }
        val totalPrice = cartItems.entries.sumByDouble { it.key.price * it.value }
        val formattedTotalPrice = String.format("%.2f", totalPrice)

        builder.setMessage("购物车商品: ${if (items.isEmpty()) "无" else items.joinToString(", ")}\n总价: ￥$formattedTotalPrice")
        builder.setPositiveButton("修改") { dialog, _ ->
            showModifyCartDialog()
        }
        builder.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }

        builder.create().show()
    }

    private fun showModifyCartDialog() {
        val builder = AlertDialog.Builder(requireContext())
        builder.setTitle("修改购物车")

        val items = cartItems.map { "${it.key.name} x${it.value}" }
        builder.setItems(items.toTypedArray()) { dialog, which ->
            val product = cartItems.keys.elementAt(which)
            modifyProductQuantity(product)
        }

        builder.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }

        builder.create().show()
    }

    private fun modifyProductQuantity(product: Product) {
        val builder = AlertDialog.Builder(requireContext())
        builder.setTitle("修改数量")

        val currentQuantity = cartItems[product] ?: 0
        val input = EditText(requireContext())
        input.inputType = InputType.TYPE_CLASS_NUMBER
        input.setText(currentQuantity.toString())

        builder.setView(input)
        builder.setPositiveButton("确认") { dialog, _ ->
            val newQuantity = input.text.toString().toIntOrNull() ?: 0
            if (newQuantity > 0) {
                cartItems[product] = newQuantity
            } else {
                cartItems.remove(product)
            }
            updateCartView()
            saveCartItems()
        }
        builder.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }

        builder.create().show()
    }

    inner class ProductAdapter(private val products: List<Product>) : RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {

        inner class ProductViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val nameTextView: TextView = itemView.findViewById(R.id.product_name)
            val priceTextView: TextView = itemView.findViewById(R.id.product_price)
            val imageView: ImageView = itemView.findViewById(R.id.product_image)
            val addButton: Button = itemView.findViewById(R.id.add_to_cart)

            init {
                addButton.setOnClickListener {
                    val product = products[adapterPosition]
                    cartItems[product] = cartItems.getOrDefault(product, 0) + 1
                    updateCartView()
                    saveCartItems()
                }
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_product, parent, false)
            return ProductViewHolder(view)
        }

        override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
            val product = products[position]
            holder.nameTextView.text = product.name
            holder.priceTextView.text = "￥${product.price}"
            holder.imageView.setImageResource(product.imageResId)
        }

        override fun getItemCount(): Int = products.size
    }

    private fun getCartItemCount(): Int {
        return cartItems.values.sum()
    }

    private fun updateCartView() {
        cartView.text = "购物车: ${getCartItemCount()} 件"
    }

    private fun saveCartItems() {
        val json = Gson().toJson(cartItems)
        sharedPreferences.edit().putString("cart_items", json).apply()
    }

    private fun loadCartItems() {
        val json = sharedPreferences.getString("cart_items", null)
        if (json != null) {
            try {
                val type = object : TypeToken<MutableMap<Product, Int>>() {}.type
                cartItems.putAll(Gson().fromJson(json, type))
                updateCartView()
            } catch (e: JsonSyntaxException) {
                // 处理 JSON 解析异常
                e.printStackTrace()
            }
        }
    }
}